package top.healthylife.gateway.platform.bank.api.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.basics.utils.utils.SystemThreadLocal;
import top.healthylife.gateway.core.util.SystemConfigUtils;
import top.healthylife.gateway.dto.request.req.ApiReqDto;
import top.healthylife.gateway.platform.bank.api.config.SystemConfig;
import top.heathylife.gateway.common.cons.SystemCons;
import top.heathylife.gateway.common.po.RecordRequestInfo;

import java.util.Map;

/**
 * @author : GaoZeXi
 * @date 2021/8/17 9:36
 */
@Slf4j
@ApiModel("人行请求工具类")
public class BankUtil {
    static final String RET_CODE = "retCode";
    static final String RET_INFO = "retInfo";
    static final String SUCCESS = "1";
    static final String FAILED = "0";
    static String url = "http://192.168.70.57:8080/services/{}";


    @SneakyThrows
    public static <T> T HttpRequest(ApiReqDto t, String uri, Class<T> cls) {
        //1.获取接口对应的地址
        String url = getUrl(uri);
        //2.获取账号信息
        SystemConfig systemConfigInfo = getSystemConfigInfo();
        //3.打印参数信息
        log.info("打印请求参数:{}", JSONObject.toJSONString(t));
        //4.构造请求所需的xml文件
        //4.1 入参
        String xml = t.toString();
        //4.2 账号信息
        //将请求参数信息存储到线程变量
        xml = StrUtil.format(xml, BeanUtil.beanToMap(systemConfigInfo));
        RecordRequestInfo.recordRequest(url, xml, null, "post");
        String body = HttpUtil.createPost(url).body(xml).execute().body();
        log.info("人行接口返回信息:{}", body);
        //将三方元数据存储到线程变量
        SystemThreadLocal.set(SystemCons.ORIGIN_DATA, body);
        try {
            Map<String, Object> map = XmlUtil.xmlToMap(body);
            String jsonString = JSONObject.toJSONString(map);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            JSONObject soapBody = jsonObject.getJSONObject("soap:Body");
            JSONObject responseNode = soapBody.getJSONObject("ns2:rtdsRequestResponse");
            JSONObject aReturn = responseNode.getJSONObject("return");
            String retCode = aReturn.getString(RET_CODE);
            if (retCode.equals(SUCCESS)) {
                String result = aReturn.getString("result");
                //去除头部的<![CDATA[
                String replace = result.replace("<![CDATA[", "");
                //去除尾部的]]>
                result = replace.substring(0, replace.length() - 3);
                aReturn.put("result", result);
                return aReturn.toJavaObject(cls);
            } else {
                String retInfo = aReturn.getString(RET_INFO);
                throw new BusinessException("人行数据返回错误:{}", retInfo);
            }

        } catch (Exception e) {
            if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            }
            throw new BusinessException("人行返回数据结构解析异常,请联系管理员");
        }
    }

    public static String getUrl(String uri) {
        return StrUtil.format(url, uri);
    }

    /**
     * 获取账号相关信息
     *
     * @return 账号信息
     */
    public static SystemConfig getSystemConfigInfo() {
        SystemConfig systemConfig = (SystemConfig) SystemConfigUtils.get();
        log.info("当前账号信息:{}", JSONObject.toJSONString(systemConfig));
        return systemConfig;
    }


}
